local http = require("socket.http")
local ltn12 = require("ltn12")

function HttpUtil()
    local self = {}
    -- get请求
    self.httpGet = function(u)
        local t = {}
        local r, c, h = http.request{
            url = u,
            -- 20160708 如果传入的是table的话， 就需要用一个容器来接收http body的内容， 也就是sink那个参数
            sink = ltn12.sink.table(t)}
        return r, c, h, table.concat(t)
    end

    self.httpPost = function(u,inParam)
        print("url:"..u)
        print("inParam:"..inParam)
        local response_body = {}
        local post_data = inParam
        local res, code = http.request{
            url = u,
            method = "POST",
            headers =
            {
                ["Content-Type"] = "application/json",
                ["Content-Length"] = #post_data,
            },
            source = ltn12.source.string(post_data),
            sink = ltn12.sink.table(response_body)
        }
        res = table.concat(response_body)
        print("res:"..res)
        print("code:"..code)
        return res,code
    end
    return self
end

local httputil=HttpUtil()
local url="http://xiaoniaoduiwoshuo.top/"
--local url="www.baidu.com"

local str="cy test"
--响应结果
local resStr
local res,code=httputil.httpPost(url,str)
if code ~= 200 then
    print("非200状态,code:"..code)
    return resStr
end
resStr=res
--httputil.httpGet(url)
